package com.molichuxing.services.utils;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.molichuxing.framework.utils.DateUtil;
import com.molichuxing.services.infrastructure.dto.request.create.AlipayCreateDto;
import com.molichuxing.services.infrastructure.dto.response.PrepaymentDto;
import com.molichuxing.services.sdk.alipay.AlipayConfig;

public class AlipayUtil {
	private static final Logger logger = LoggerFactory.getLogger(AlipayUtil.class);
	private final static String PREFIX = "ali";

	/**
	 * 支付宝统一下单封装参数
	 * 
	 * @param createDto
	 * @return
	 */
	public static AlipayTradeAppPayRequest orderPayParams(AlipayCreateDto createDto, AlipayConfig config) {
		AlipayTradeAppPayRequest result = new AlipayTradeAppPayRequest();

		AlipayTradeAppPayModel payModel = new AlipayTradeAppPayModel();
		// 附加数据
		payModel.setPassbackParams(createDto.getPassbackParams());
		// 商品描述
		payModel.setBody(createDto.getBody());
		// 商品的标题
		payModel.setSubject(createDto.getSubject());
		// 商户订单号(自动生成)
		payModel.setOutTradeNo(PREFIX + PaymentUtil.getPayNumber());
		// model.setTimeoutExpress("30m"); //交易超时时间
		// 支付金额
		payModel.setTotalAmount(createDto.getTotalAmount() + "");
		// 绝对超时时间
		if (createDto.getTimeExpire() != null) {
			payModel.setTimeExpire(DateUtil.formatTime(createDto.getTimeExpire(), "yyyy-MM-dd HH:mm"));
		}
		// 销售产品码，商家和支付宝签约的产品码
		payModel.setProductCode(config.getProductCode());
		// 业务数据
		result.setBizModel(payModel);
		// 异步回调地址（后台）
		result.setNotifyUrl(config.getNotifyUrl());

		logger.info("支付宝统一下单封装参数：" + JSONObject.toJSONString(result));
		return result;
	}

	/**
	 * 统一下单回显参数
	 * 
	 * @param config
	 * @param reqData
	 * @param respData
	 * @return
	 */
	public static PrepaymentDto orderPayResponseParams(AlipayConfig config, AlipayTradeAppPayRequest reqData,
			AlipayTradeAppPayResponse respData) {
		PrepaymentDto result = new PrepaymentDto();
		Map<String, String> repData = new HashMap<>();
		repData.put("payParam", respData.getBody());

		logger.info("支付宝预支付单返回页面参数：" + repData.toString());
		result.setRequestData(JSONObject.toJSONString(repData));
		result.setOutTradeNo(((AlipayTradeAppPayModel) reqData.getBizModel()).getOutTradeNo());
		return result;
	}

}
